﻿using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 获取工艺路线列表
    /// </summary>
    public class SearchProcessRouteHandler : IRequestHandler<SearchProcessRouteCommand, Result<PageResultDto<ProcessRouteDtos>>>
    {
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// 工艺路线仓储
        /// </summary>
        private readonly IBaseRepository<ProcessRoutes> _processRouteRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchProcessRouteHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processRouteRepository"></param>
        /// <param name="logger"></param>
        /// <param name="db"></param>
        public SearchProcessRouteHandler(IBaseRepository<ProcessRoutes> processRouteRepository,
                                         ILogger<SearchProcessRouteHandler> logger,
                                         ISqlSugarClient db)
        {
            _processRouteRepository = processRouteRepository;
            _logger = logger;
            _db = db;
        }

        /// <summary>
        /// 获取工艺路线列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<ProcessRouteDtos>>> Handle(SearchProcessRouteCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<ProcessRouteDtos>>() { Code = (int)CommonErrorCode.Search };
            //创建工艺路线分页
            var page = new PageResultDto<ProcessRouteDtos>() { TotalCount = 0, PageCount = 0, List = new List<ProcessRouteDtos>() };
            try
            {
                //总条数
                RefAsync<int> totalCount = 0;
                //总页数
                RefAsync<int> totalPage = 0;
                //查询数据
                var query = _db.Queryable<ProcessRoutes, MaterialManagement>((p, m) => p.MaterialId == m.MaterialId)
                    .Select((p, m) => new ProcessRouteDtos()
                    {
                        ProcessRouteId = p.ProcessRouteId,
                        ProcessRouteNo = p.ProcessRouteNo,
                        ProcessRouteName = p.ProcessRouteName,
                        ProcessVersion = p.ProcessVersion,
                        ProcessDesc = p.ProcessDesc,
                        MaterialId = p.MaterialId,
                        ProcessStatus = p.ProcessStatus,
                        AuditStatus = p.AuditStatus,
                        IsDeleted = p.IsDeleted,
                        CreatedOwner = p.CreatedOwner,
                        CreatedTime = p.CreatedTime,
                        UpdateOwner = p.UpdateOwner,
                        UpdateTime = p.UpdateTime,
                        ExamineOwner = p.ExamineOwner,
                        ExamineTime = p.ExamineTime,
                        MaterialName = m.MaterialName,
                    });
                //工艺编码模糊查
                if (!string.IsNullOrEmpty(request.ProcessRouteNo))
                {
                    query = query.Where(p => p.ProcessRouteNo.Contains(request.ProcessRouteNo));
                }
                //工艺名称模糊查
                if (!string.IsNullOrEmpty(request.ProcessRouteName))
                {
                    query = query.Where(p => p.ProcessRouteName.Contains(request.ProcessRouteName));
                }
                //物料精确查
                if (request.MaterialId != 0)
                {
                    query = query.Where(p => p.MaterialId == request.MaterialId);
                }
                //状态精确查
                if (request.ProcessStatus != 0)
                {
                    query = query.Where(p => p.ProcessStatus == request.ProcessStatus);
                }
                var list = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                //总条数
                page.TotalCount = totalCount;
                //总页数
                page.PageCount = totalPage;
                //跳过几条显示几条
                page.List = list;
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取工艺路线列表成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取工艺路线列表异常" + ex.Message;
                _logger.LogError("获取工艺路线列表异常" + ex.Message);
            }
            return result;
        }
    }
}
